package com.suxii.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

public class WaveView extends View {
    private Paint paint;
    private Path path;

    private ValueAnimator animator;

    public WaveView(Context context) {
        this(context,null);
    }

    public WaveView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public WaveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint=new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(0xaa7b6cf9);
        paint.setStrokeWidth(1);
        path=new Path();
        paint.setAntiAlias(true);

        amin();
        animator.start();
    }

    /*
    三角函数画弦图
    y=A*sin(wx+b)+k
     */

    private float A=30,w=0.004f,b=0,k=80;
    private float move=0.04f;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawSin(canvas);
        drawCos(canvas);
    }

    private void drawCos(Canvas canvas) {
        path.reset();

        path.moveTo(0,getHeight());

        float y,x;
        for (x = 0; x < getWidth(); x+=2) {
            y= (float) (-A*Math.sin(w*x+b)+k);
            path.lineTo(x,getHeight()-y);
        }
        path.lineTo(getWidth(),0);
        path.lineTo(0,0);
        path.close();
        canvas.drawPath(path,paint);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, Paint.FILTER_BITMAP_FLAG));

    }

    private void drawSin(Canvas canvas) {
        path.reset();

        path.moveTo(0,getHeight());

        float y,x;
        for (x = 0; x < getWidth(); x+=2) {
            y= (float) (A*Math.sin(w*x+b)+k);
            path.lineTo(x,getHeight()-y);
            //Log.e("aa","x:"+x+"__y:"+y);
        }
        path.lineTo(getWidth(),0);
        path.lineTo(0,0);
        path.close();
        canvas.drawPath(path,paint);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, Paint.FILTER_BITMAP_FLAG));

    }

    private void amin(){
        animator=ValueAnimator.ofFloat(0,getWidth());
        animator.setDuration(1000);
        animator.setRepeatCount(ValueAnimator.INFINITE);//设置循环
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(v -> {
            invalidate();
            if (b<getWidth()) {
                b += move;
            }else {
                b=0;
            }
            //Log.e("aa", String.valueOf(b));
        });

    }

}
